package com.yr.visa.util.anno;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

import org.springframework.util.ReflectionUtils;

import com.gargoylesoftware.htmlunit.html.DomElement;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlRadioButtonInput;
import com.gargoylesoftware.htmlunit.html.HtmlSelect;

public class VisaMetaParse {

	
	public static void parse(HtmlPage page,Object v){
		
		Field[] fields = v.getClass().getDeclaredFields();
		for (Field f : fields) {
			if (f.isAnnotationPresent(VisaMetaInfo.class)) {
				VisaMetaInfo meta=	f.getAnnotation(VisaMetaInfo.class);
				String id = meta.id();
				Minfo minfo =meta.type();
				String _v =doGetMethod(v, f.getName()).toString();
				switch(minfo){
					case INPUT:(page.getElementById(id)).setAttribute("value", _v);
					case SELECT:((HtmlSelect)page.getElementById(id)).getOptionByText(_v).setSelected(true);
					case RADIO :handlerRadio(page, id, _v);
				}
				
			}
		}
	}
	
	
	private static void handlerRadio(HtmlPage page,String name,String text){
		 List<DomElement> reles =page.getElementsByName(name);
		 if(reles != null){
			 for(DomElement d: reles){
				 HtmlRadioButtonInput radio = (HtmlRadioButtonInput)d;
				 if(radio.getValueAttribute().equals(text)){
					 radio.setChecked(true); break;
				 }
			 }
		 }
	}
	
	private static Object doGetMethod(Object q, String fieldName) {
		try {
			String methodEnd = "get"
					+ fieldName.substring(0, 1).toUpperCase()
					+ fieldName.substring(1);
			return ReflectionUtils.findMethod(q.getClass(), methodEnd).invoke(
					q);
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
}
